package ua.at.javac.cron;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ua.at.javac.server.Database;

/**
 * Обработка сервера gismeteo
 * 
 * @author Michael.Michaelovich
 * @version 98
 * @since 2012
 */
public class SortURLGisMeteo {
	
public SortURLGisMeteo(){
		
		pogoda.put("Ясно", "0");					pogoda.put(" сильный снег, снег с дождем", "40.0");
		pogoda.put("Малооблачно", "35");			pogoda.put(" небольшой дождь, морось", "4.0");
		pogoda.put("Облачно", "65");				pogoda.put(" небольшой дождь, гроза", "5.0");
		pogoda.put("Пасмурно", "100");				pogoda.put(" дождь, гроза", "7.0");
		pogoda.put(" небольшой дождь", "3.0");		pogoda.put("без осадков", "0.0");
		pogoda.put(" дождь", "6.0");				pogoda.put(" дымка", "0.7");
		pogoda.put(" сильный дождь", "25.0");		pogoda.put("", "");
		pogoda.put(" сильный снег", "36.0");		pogoda.put("", "");
		pogoda.put(" снег", "15.0");				pogoda.put("", "");
		pogoda.put(" небольшой снег", "10.0");		pogoda.put("", "");
		
	}

	public void start() throws Exception {
	
	Database db = new Database();
	// db.getConnection();
	city = db.getSiteCity("gismeteo");
	for(String[] c : city){
		String httpLink = c[3];
		//String cityStr = c[2];
	 	String site_id = c[1];
	 	//System.out.println(cityStr);
		//http://www.gismeteo.ua/city/weekly/5053/ Харьков
		//http://www.gismeteo.ua/city/weekly/4944/ Киев
	
		sbuf0 = new Reader(httpLink).readUrl();	
		indexDate = 0;
		indexSky = 0;
		indexWind = 0;
		indexTemp = 0;
		forecastDay = 0;
		
		for (int j = 0; j < 6; j++){
			
			for(int i = 1; i < 5; i++) {															
							 
				indexDate = sbuf0.indexOf(Date, indexDate);//нахождение даты
			if(indexDate<0){
				break;
				}
				int startCountDate = indexDate + Date.length();
				int endCountDate = sbuf0.indexOf(Probel,startCountDate);											 
				dateOut = sbuf0.substring(startCountDate, endCountDate);
				indexDate++;
				
				//System.out.println(dateOut);
				
				indexSky = sbuf0.indexOf(Sky, endCountDate);//нахождение состояния неба
				int startCountSky = indexSky + Sky.length();
				int endCountSky = sbuf0.indexOf(Menshe, startCountSky);
				skyOut = sbuf0.substring(startCountSky, endCountSky);
				indexSky++;
				
				//System.out.println("Состояние неба: "+skyOut);
						 
				indexTemp = sbuf0.indexOf(temperature, endCountSky);//нахождение температуры
				int startCountTemp = indexTemp+temperature.length();
				int endCountTemp = sbuf0.indexOf(Menshe,startCountTemp);								
				tempOut = sbuf0.substring(startCountTemp, endCountTemp);
				tempOut = tempOut.replace("&minus;", "-").replace("+", "");
						
				//System.out.println("Температура: "+tempOut);
			
				int startCountPressure = sbuf0.indexOf(pressureStr, endCountTemp)+pressureStr.length();//нахождение значения давления
				int endCountPressure = sbuf0.indexOf(Menshe, startCountPressure);
				pressureOut = sbuf0.substring(startCountPressure, endCountPressure);
				
				//System.out.println("Давление: "+pressureOut);
				
				indexWind = sbuf0.indexOf(Wind, endCountPressure)+Wind.length();//нахождение направления ветра
				int startCountWind = sbuf0.indexOf(Bolshe, indexWind)+Bolshe.length();
				int endCountWind = sbuf0.indexOf(Menshe, startCountWind);
				windOut = sbuf0.substring(startCountWind, endCountWind);
				
				//System.out.println("Направление ветра: "+windOut);
				
				int startCountSpeedWind = sbuf0.indexOf(Teg0, endCountWind)+Teg0.length();//нахождение значения скорости ветра
				int endCountSpeedWind = sbuf0.indexOf(Menshe, startCountSpeedWind);
				speedWindOut = sbuf0.substring(startCountSpeedWind, endCountSpeedWind);
				
				// System.out.println("Скорость ветра: "+speedWindOut);
				
				int startCountWet = sbuf0.indexOf(Teg, endCountSpeedWind)+Teg.length();//нахождение значения влажности воздуха
				int endCountWet = sbuf0.indexOf(Menshe, startCountWet);
				wetOut = sbuf0.substring(startCountWet, endCountWet);
				
				//System.out.println("Влажность: "+wetOut);
				
				indexWind++;																							
			  
				
				// преобразование для облачности(cloudiness)
				int cloudiness = getCloudiness(skyOut);															 
				int temperature = Integer.parseInt(tempOut);
				int humidity = Integer.parseInt(wetOut);
				int pressure = Integer.parseInt(pressureOut);
				int windSpeed = Integer.parseInt(speedWindOut);
				int wind_id = 1;				
				double precipitation = getRainfall(skyOut);
				
				// System.out.println(skyOut);
				//System.out.println("Облачность:  "+cloudiness);
				//System.out.println("Осадки:  "+precipitation);
				
			 // преобразование для направления ветра
				wind_id = getWindId(windOut);
			  
				journalR = new JournalRow(dateOut, Integer.parseInt(site_id), i, cloudiness, 
		  			  					  temperature, precipitation, humidity, pressure, windSpeed, 
		  			  					  wind_id, forecastDay);
		  	  	weatherList.add(journalR);				
			// добавление данных в журнал БД
				/*db.addToJournal(dateOut, Integer.parseInt(site_id), i, cloudiness, temperature, 
							precipitation, humidity, pressure, windSpeed, 
							wind_id, forecastDay);*/ 
				
			 // преобразование для периода ночь-4, утро -1, день -2, вечер-3
				//System.out.println(i);				
				
		}
			forecastDay++;
	  }
	}
				db.addToJournalList(weatherList);
}

	/**
	 * @param wind_id
	 * @return
	 */
	private int getWindId(String windOut) {
		int wind_id = 1;
		if (windOut.equals("С"))wind_id = 1;
		if (windOut.equals("СВ"))wind_id = 2;
		if (windOut.equals("В"))wind_id = 3;
		if (windOut.equals("ЮВ"))wind_id = 4;
		if (windOut.equals("Ю"))wind_id = 5;
		if (windOut.equals("ЮЗ"))wind_id = 6;
		if (windOut.equals("З"))wind_id = 7;
		if (windOut.equals("СЗ"))wind_id = 8;
		if (windOut.equals("Ш"))wind_id = 9;		//добавить в таблицу базы "ШТИЛЬ" !!!!!!! - OK!
		return wind_id;
	}
	/**
	 * 
	 * @param skyOut
	 * @return
	 */
	private int getCloudiness(String skyOut){
		String markEndCloudiness = ",";
		String cloudStr;
		if(skyOut.contains(markEndCloudiness)){
			int endCloudiness = skyOut.indexOf(markEndCloudiness);
			cloudStr = skyOut.substring(0, endCloudiness);
		}
		else cloudStr = skyOut; 
		int cloudiness = Integer.parseInt(pogoda.get(cloudStr));
		return cloudiness;
	}
	/**
	 * 
	 * @param skyOut
	 * @return
	 */
	private double getRainfall(String skyOut){
		String markStartRainfall = ",";
		String rainfallStr;
		if(skyOut.contains(markStartRainfall)){
			int startRainfall = skyOut.indexOf(markStartRainfall) + markStartRainfall.length();
			rainfallStr = skyOut.substring(startRainfall);			
		}
		else rainfallStr = "без осадков";
		double rainfall = Double.parseDouble(pogoda.get(rainfallStr));
		return rainfall;
	}
	private Map<String, String> pogoda = new HashMap<String, String>();
	private JournalRow journalR;
	private List<JournalRow> weatherList = new ArrayList<JournalRow>();
	private List<String[]> city;
	private String Probel = " ";
	private String temperature = "<td class=\"temp\"><span class='value m_temp c'>";
	private String Menshe = "<";
	private String Bolshe = ">";
	private String Sky = "td class=\"cltext\">";
	private String pressureStr = "<span class='value m_press torr'>" ;
	private String Date = "Local: ";
	private String Teg = "<td>";
	private String Teg0 = "<span class='value m_wind ms'>";
	private String Wind = "<td><dl class=\"wind\"><dt class=\"";
	private StringBuffer sbuf0;
	private String pressureOut;
	private String wetOut;
	private String tempOut;
	private String windOut;
	private String dateOut;
	private String skyOut;
	private String speedWindOut;
	private int indexWind = 0;
	private int indexTemp = 0;
	private int indexDate = 0;
	private int indexSky = 0;
	private int forecastDay = 0;
}
